// image_decoder.cc
#include "image_decoder.hpp"

// 初始化解码器
MJpegDecoder* mjpeg_decoder_init(uint32_t width, uint32_t height) {
    MJpegDecoder* decoder = (MJpegDecoder*)malloc(sizeof(MJpegDecoder));
    if (!decoder) return NULL;
    
    // 初始化TurboJPEG解压缩句柄
    decoder->handle = tjInitDecompress();
    if (!decoder->handle) {
        fprintf(stderr, "TurboJPEG初始化失败: %s\n", tjGetErrorStr2(decoder->handle));
        free(decoder);
        return NULL;
    }
    
    // 预分配RGB888缓冲区
    decoder->buffer_size = width * height * 3;
    decoder->output_buffer = (unsigned char*)malloc(decoder->buffer_size);
    if (!decoder->output_buffer) {
        tjDestroy(decoder->handle);
        free(decoder);
        return NULL;
    }
    
    return decoder;
}

// JPEG解码处理
int mjpeg_decoder_process(MJpegDecoder* decoder, const unsigned char* mjpeg_data, 
                          size_t data_size, uint32_t width, uint32_t height, 
                          unsigned char ** out_rgb) 
{
    if (!decoder || !mjpeg_data || data_size == 0) {
        fprintf(stderr, "解码输入数据不符合要求\n");
        return -1;
    }
    
    int jpeg_width, jpeg_height, jpeg_subsamp, jpeg_colorspace;
    
    // 1. 解析JPEG头信息
    if (tjDecompressHeader3(decoder->handle, mjpeg_data, data_size, 
                           &jpeg_width, &jpeg_height, &jpeg_subsamp, &jpeg_colorspace) != 0) 
    {
        fprintf(stderr, "JPEG头解析失败: %s\n", tjGetErrorStr2(decoder->handle));
        return -2;
    }
    
    // 2. 验证分辨率
    if (jpeg_width != (int)width || jpeg_height != (int)height) {
        fprintf(stderr, "分辨率不匹配: 期望 %dx%d, 实际 %dx%d\n", 
                width, height, jpeg_width, jpeg_height);
        return -3;
    }
    
    // 3. 执行解压缩 (TJPF_RGB对应RGB888格式)
    if (tjDecompress2(decoder->handle, mjpeg_data, data_size, decoder->output_buffer,
                     width, 0, height, TJPF_RGB, TJFLAG_FASTDCT) != 0) 
    {
        fprintf(stderr, "JPEG解压缩失败: %s\n", tjGetErrorStr2(decoder->handle));
        return -4;
    }
    
    *out_rgb = decoder->output_buffer;
    return 0;
}

// 释放解码器资源
void mjpeg_decoder_release(MJpegDecoder* decoder) {
    if (!decoder) return;
    
    // 释放TurboJPEG句柄
    if (decoder->handle) {
        tjDestroy(decoder->handle);
        decoder->handle = NULL;
    }
    
    // 释放RGB缓冲区
    if (decoder->output_buffer) {
        free(decoder->output_buffer);
        decoder->output_buffer = NULL;
        decoder->buffer_size = 0;
    }
    
    free(decoder);
}